import sys
import ldap
import model
import yaml
import sqlite3
import web
from web.wsgiserver import CherryPyWSGIServer
from web.session import DBStore
import bottle
  
class MySSL(bottle.ServerAdapter):  
    def run(self, handler):  
        
        server = CherryPyWSGIServer((self.host, self.port), handler)  
        from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter 
        server.ssl_adapter= pyOpenSSLAdapter('./config/server.crt','./config/server.key')
        try:  
            server.start()  
        finally:  
            server.stop()  



conf = yaml.load(file('./config/conf.yaml'))

app = bottle.app()  

bottle.server_names['myssl'] = MySSL  
model.set_session('username','')
model.set_session('is_auth','false')


@app.route('/debug')
def do_debug():
    result={}
    username= model.get_session('username')
    output = bottle.template("yes\n{{username}}\n", username=username)
    return output

@app.route('/login',method='POST')
def do_post():
    result= {}

    result['is_auth']= model.get_session('is_auth')
    result['username']= model.get_session('username')    
    result['service']= model.get_session('service')    

    service = model.get_session('service')

    if (result['is_auth'] == 'true'):
        output = bottle.template('login', dico=result)
        return output

    username = bottle.request.POST.get('username','').strip()
    password = bottle.request.POST.get('password','').strip()

    try:
        server = 'ldap://localhost'
        l = ldap.initialize(server)
        dn = "uid=%s,ou=People,dc=blogdns,dc=org" % (username)
        
        if (l.simple_bind_s( dn, password )[0] == 97):
            result['is_auth']='true'
            model.set_session('username',username)
            model.set_session('is_auth','true')
            if (service != ''):
                bottle.redirect('/login?service='+service)
    except ldap.LDAPError, e:
            result['is_auth']= 'false'	
            model.set_session('is_auth','false')
            result['reason']= e.message	




    output = bottle.template('login', dico=result)
    return output

@app.route('/login',method='GET')

def do_login():
    
    result= {}
    result['is_auth']= model.get_session('is_auth')	
    result['username']= model.get_session('username')
    result['service']= model.get_session('service')    


    service = bottle.request.GET.get('service','').strip()
    model.set_session('service',service)

    if (result['is_auth'] =='true' and service !=''):
        ticket = model.insert_ticket(username=result['username'],service=service,client_hostname='localhost',type='ServiceTicket')
        bottle.redirect(service+'?ticket='+ticket)
    else:
        output = bottle.template('login', dico=result)
        return output

@app.route('/logout',method='GET')

def do_logout():
    model.set_session('username','')
    model.set_session('is_auth','false')
    model.set_session('service','')
    bottle.redirect('/login')     


@app.route('/validate',method='GET')
def do_validate():
    result={}
    username=model.get_session('username')
    result['username']=username
    is_auth=model.get_session('is_auth')
    if (is_auth == 'false'):
        bottle.redirect('/login')
    ticket=bottle.request.GET.get('ticket','').strip()
    service=bottle.request.GET.get('service','').strip()
    
    bottle.response.headers['Content-Type'] = 'text/plain'
    if model.validate_ticket(service,ticket,username):
        output = bottle.template("yes\n{{username}}\n", username=username)
        return output
    else:
        return "no"

@app.route('/serviceValidate',method='GET')
def do_service_validate():
    result={}
    username=model.get_session('username')
    result['username']=username
    is_auth=model.get_session('is_auth')
    if (is_auth == 'false'):
        bottle.redirect('/login')
    ticket=bottle.request.GET.get('ticket','').strip()
    service=bottle.request.GET.get('service','').strip()
    
    bottle.response.headers['Content-Type'] = 'application/xml'
    if model.validate_ticket(service,ticket,username):
        output = bottle.template('casResponse', username=username)
    else:
        output = bottle.template('casNoResponse')
    return output

@app.route('/proxyValidate',method='GET')
def do_proxy_validate():
    result={}
    username=model.get_session('username')
    result['username']=username
    is_auth=model.get_session('is_auth')
    if (is_auth == 'false'):
        bottle.redirect('/login')
    ticket=bottle.request.GET.get('ticket','').strip()
    service=bottle.request.GET.get('service','').strip()
    
    bottle.response.headers['Content-Type'] = 'application/xml'
    if model.validate_ticket(service,ticket,username):
        output = bottle.template('casResponse', username=username)
    else:
        output = bottle.template('casNoResponse')
    return output


@app.route('/help')
def help():
    return bottle.static_file('help.html', root='./public/')

@app.route('/<path:path>')
def callback(path):
    return bottle.static_file(path,root='./public/')

@app.error(403)
def mistake403(code):
    return 'There is a mistake in your url!'

@app.error(404)
def mistake404(code):
    return 'Sorry, this page does not exist!'


bottle.debug(True)
bottle.run(port=443, host='0.0.0.0',server='myssl')
